<template>
  <page-meta
    :page-style="`overflow:${openDrawer || showSharePopup ? 'hidden' : 'visible'};`"
  ></page-meta>
  <PageContainer>
    <view class="container">
      <FillOutTheForm v-if="currIndex === 0"></FillOutTheForm>
      <FormTemplate v-if="currIndex === 1" @reported-data="handleReportedData"></FormTemplate>
      <CollectRecord v-if="currIndex === 2"></CollectRecord>
      <customTabBar @change="(index) => (currIndex = index)"></customTabBar>
    </view>
  </PageContainer>

  <CustomShare v-model:visible="showSharePopup" :z-index="999" @register="customShareRegister" />
</template>

<script lang="ts" setup>
  /* serviceForm 服务表单 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import customTabBar from './components/customTabBar/index.vue';
  import FillOutTheForm from './components/FillOutTheForm/index.vue';
  import CollectRecord from './components/CollectRecord/index.vue';
  import FormTemplate from './components/FormTemplate/index.vue';
  import { provide, ref } from 'vue';
  import { onPageScroll, onShareAppMessage, onShow } from '@dcloudio/uni-app';
  import type { IFormTemplate } from '@/api/serviceForm/types';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { useAppStore } from '@/store/modules/app';
  import { createShareQuery, useAppShare } from '@/hooks/core/useAppShare';
  import { addAppShareLog } from '@/api';
  import { useSaveFile } from '@/hooks/core/useSaveFile';

  const { setWxSharePath } = useAppShare();
  const { hasShareImgConfig } = useAppStore();
  const { downloadFile } = useSaveFile();
  const openDrawer = ref<boolean>(false);

  provide('openDrawer', openDrawer);

  const currIndex = ref(0);

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    { setWxShareOptions, setShareLogId, setPosterDrawData, setButtons, setInternalLinkOptions },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  const shareCache = new Map<number, { codeImg: string; shareLogId: number; posterImg: string }>(
    [],
  );
  async function handleReportedData(item: IFormTemplate) {
    const shareCacheItem = shareCache.get(item.id);
    const res = hasShareImgConfig(ShareTypeEnum.invitationToFillOutServiceForm);
    if (!shareCacheItem) {
      uni.showLoading({ title: '分享参数准备中...', mask: true });
    }
    const query = {
      serviceTicketFormId: item.id as number,
    };
    setInternalLinkOptions({
      name: 'serviceFormFilling',
      options: query,
    });
    const routeQuery = createShareQuery(query);
    await setWxShareOptions([
      {
        path: setWxSharePath({ name: 'serviceFormFilling', options: query }),
        imageUrl: res?.iconUrl,
        title: item.title,
      },
    ]);
    let shareLogId = shareCacheItem?.shareLogId;
    let codeImg = shareCacheItem?.codeImg;
    if (!shareCache.has(item.id)) {
      const res = await addAppShareLog({
        path: 'serviceFormFilling',
        query: JSON.stringify(routeQuery),
      });
      shareLogId = res.id;
      codeImg = await createMiniCode({ shareLogId });
      const img = item.img ? await downloadFile(item.img) : '';
      setButtons({
        share: true,
        poster: !!img,
        copyLink: true,
        insertOffiaccount: true,
      });
      await setPosterDrawData([img]);
      shareCache.set(item.id, { codeImg, shareLogId, posterImg: img });
      uni.hideLoading();
    } else {
      setButtons({
        share: true,
        poster: !!shareCacheItem?.posterImg,
        copyLink: true,
        insertOffiaccount: true,
      });
      await setPosterDrawData([shareCacheItem?.posterImg || '']);
    }

    setShareLogId(shareLogId as number);
    showSharePopup.value = true;
  }

  onShow(() => shareCache.clear());

  onShareAppMessage(() => ({}));
  onPageScroll(() => {});

  wx.hideShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
  });
</script>

<style lang="scss" scoped></style>
